import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/daily',
    name: 'daily',
    component: () => import('../views/DailyView.vue'),
    meta: { title: '日常笔记' }
  },
  {
    path: '/document',
    name: 'document',
    component: () => import('../views/DocumentView.vue'),
    meta: { title: '文档笔记' }
  },
  {
    path: '/labels',
    name: 'labels',
    component: () => import('../views/LabelsView.vue'),
    meta: { title: '标签云' }
  },
  {
    path: '/label/:labelId',
    name: 'label-notes',
    component: () => import('../views/LabelNotesView.vue'),
    meta: { title: '标签笔记' }
  },
  {
    path: '/note/:type/:id',
    name: 'note-detail',
    component: () => import('../views/NoteDetailView.vue'),
    meta: { title: '笔记详情' }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/SearchView.vue'),
    meta: { title: '搜索' }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/UserProfileView.vue'),
    meta: { title: '个人中心', requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('../views/NotFoundView.vue'),
    meta: { title: '页面未找到' }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 若依笔记博客`
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({ name: 'login', query: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router